const autoEffectCycleType = [
  {
    type: '不重复',
    value: 0
  },
  {
    type: '按周',
    value: 1
  },
  {
    type: '自定义',
    value: 2
  }
];

const weekOpt = [
  {
    type: '周一',
    value: '2'
  },
  {
    type: '周二',
    value: '3'
  },
  {
    type: '周三',
    value: '4'
  },
  {
    type: '周四',
    value: '5'
  },
  {
    type: '周五',
    value: '6'
  },
  {
    type: '周六',
    value: '7'
  },
  {
    type: '周日',
    value: '1'
  }
];
import utils from '@/mixins/utils.js';
export default {
  name: 'tideChannelList',
  mixins: [utils],
  data() {
    return {
      autoEffectCycleType,
      weekOpt,
      tideChannel: {
        list: []
      },
      enterChannelList: [],
      leaveChannelList: [],
      originData: null
    };
  },
  created() {
    this.getTideChannelList();
    this.getChannelList();
  },
  methods: {
    getTideChannelList() {
      API.fetchGet('/operatorPark/getParkCloudTideChannelList', {
        parkID: this.$route.query.parkId
      }).then(
        res => {
          this.originData = JSON.parse(JSON.stringify(res.data));
          res.data.forEach(item => {
            let uiOpt = {
              curEditItem: null,
              curType: '',
              weekSelected: [],
              dateSelected: [],
              isEdit: false,
              isShow: false,
              timeList: [
                {
                  timeRang: ['', '']
                }
              ]
            };
            if(item.tideType==1){
              item.manualChangeEnable = true
            }
            if (item.autoChangeEnable) {
              uiOpt.curType = 'autoChangeEnable';
              uiOpt.timeList = [];
              const effectTimerArray = JSON.parse(item.autoEffectTimer).effectTimerArray;
              effectTimerArray.forEach(item => {
                uiOpt.timeList.push({
                  timeRang: item.split('-')
                });
              });

              if (item.autoEffectCycleType === 1) {
                uiOpt.weekSelected = JSON.parse(item.autoEffectCycleContent).effectCycleArray;
              }

              if (item.autoEffectCycleType === 2) {
                uiOpt.dateSelected = JSON.parse(item.autoEffectCycleContent).effectCycleArray;
              }
            }

            if (item.manualChangeEnable) {
              uiOpt.curType = 'manualChangeEnable';
            }

            item.uiOpt = uiOpt;

            item.autoEffectCycleContent = {
              effectCycleArray: []
            };

            item.autoEffectTimer = {
              effectTimerArray: []
            };

            item.tideType += ''

          });

          this.tideChannel.list = res.data;
        },
        err => {}
      );
    },
    getChannelList() {
      API.fetchGet(`/operatorPark/byParkID/${this.$route.query.parkId}`).then(
        res => {
          res.data.forEach(item => {
            if (item.entranceType === 1) {
              this.enterChannelList.push(item);
            }

            if (item.entranceType === 2) {
              this.leaveChannelList.push(item);
            }
          });
        },
        err => {}
      );
    },
    typeChange(val, item) {
      if (val === 'manualChangeEnable') {
        item.manualChangeEnable = true;
        item.autoChangeEnable = false;
      }

      if (val === 'autoChangeEnable') {
        item.autoChangeEnable = true;
        item.manualChangeEnable = false;
      }
    },
    addTime(list) {
      list.push({
        timeRang: ['', '']
      });
    },
    delTime(list, index) {
      list.splice(index, 1);
    },
    editItem(item, index, list) {
      item.uiOpt.curEditItem = JSON.parse(JSON.stringify(item));
      item.uiOpt.curEditItem.isShow = true;
      item.uiOpt.curEditItem.isEdit = false;

      if (!item.uiOpt.isEdit) {
        item.uiOpt.isShow = true;
      }
      item.uiOpt.isEdit = !item.uiOpt.isEdit;
    },
    cancleEdit(item, index) {
      this.tideChannel.list.splice(index, 1, item.uiOpt.curEditItem);
    },
    confirmFn(msg) {
      return new Promise(resolve => {
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'mgr-msg-box',
          confirmButtonClass: 'el-button el-button--danger'
        })
          .then(() => {
            resolve(true);
          })
          .catch(() => {
            resolve(false);
          });
      });
    },
    async delTideChannel(item, index, list) {
      const canDel = await this.confirmFn('您确定要删除此潮汐通道?');
      if (!canDel) return;
      const delItem = this.originData.filter(citem => citem.id === item.id)[0];
      const delList = [delItem];
      API.fetchPost('/operatorPark/delParkCloudTideChannel', delList).then(
        res => {
          if (res.status === 1) {
            this.showToast('删除潮汐通道成功', 1, 1500);
            list.splice(index, 1);
          } else {
            this.showToast(res.message, 2, 1500);
          }
        },
        err => {
          console.log(err);
        }
      );
    },
    checkTime(val, item, index, timeList) {
      if (this.vaidEffectTimeArray(val[0], val, index, timeList)) {
        this.showToast('生效时段不可重合，请重设', 2, 1500);
        timeList.splice(index, 1, {
          timeRang: ['', '']
        });
      }
    },
    vaidEffectTimeArray(val, item, index, timeList) {
      const self = this;
      let isEffectTime = false;
      let curTime = this.getTime(val);
      const cur_time_item = item;

      timeList.some((item, cindex) => {
        if (cindex !== index) {
          const s_time = item.timeRang[0] ? self.getTime(item.timeRang[0]) : null;
          const e_time = item.timeRang[1] ? self.getTime(item.timeRang[1]) : null;
          if (s_time !== null && e_time !== null) {
            if (curTime >= s_time && curTime <= e_time) {
              isEffectTime = true;
              return true;
            } else if (cur_time_item[0] && cur_time_item[1] && self.getTime(cur_time_item[0]) < s_time && self.getTime(cur_time_item[1]) > e_time) {
              isEffectTime = true;
              return true;
            }
          }
        } else if (cur_time_item[0] && cur_time_item[1] && self.getTime(cur_time_item[0]) == self.getTime(cur_time_item[1])) {
          isEffectTime = true;
          return true;
        }
      });
      return isEffectTime;
    },
    getTime(time) {
      const d = new Date();
      return new Date([d.getFullYear(), d.getMonth() + 1, d.getDate()].join('/') + ' ' + time).getTime();
    },
    saveEdit(item) {
      const self = this;
      let saveData  = null;
      if(item.tideType==1){ //同进出通道
        saveData = {
          enterChannelId: item.enterChannelId,
          id: item.id,
          leaveChannelId: item.leaveChannelId,
          parkId: item.parkId,
          tideName: item.tideName,
          tideType: 1
        };
      }else{
        saveData = JSON.parse(JSON.stringify(item));
        if (saveData.autoChangeEnable) {
          saveData.autoEffectTimer.effectTimerArray = [];
          saveData.uiOpt.timeList.forEach(item => {
            saveData.autoEffectTimer.effectTimerArray.push(item.timeRang.join('-'));
          });
  
          if (saveData.autoEffectCycleType === 0) {
            const d = new Date();
            saveData.autoEffectCycleContent.effectCycleArray = [];
            saveData.autoEffectCycleContent.effectCycleArray.push(`${d.getFullYear()}-${this.add0(d.getMonth() + 1)}-${this.add0(d.getDate())}`);
            saveData.uiOpt.timeList.some(item => {
              if (self.getTime(item.timeRang[0]) < d.getTime() - d.getMinutes() * 1000) {
                let next_day = d.getTime() + 1000 * 60 * 60 * 24;
                next_day = new Date(next_day);
                saveData.autoEffectCycleContent.effectCycleArray.push(`${next_day.getFullYear()}-${this.add0(next_day.getMonth() + 1)}-${this.add0(next_day.getDate())}`);
                return true;
              }
            });
          }
  
          if (saveData.autoEffectCycleType === 1) {
            saveData.autoEffectCycleContent.effectCycleArray = saveData.uiOpt.weekSelected;
          }
  
          if (saveData.autoEffectCycleType === 2) {
            saveData.autoEffectCycleContent.effectCycleArray = saveData.uiOpt.dateSelected;
          }
        }
  
        if (saveData.manualChangeEnable) {
          saveData.autoEffectTimer = null;
          saveData.autoEffectCycleContent = null;
        }
  
        if (saveData.autoChangeEnable) {
          saveData.autoEffectCycleContent = JSON.stringify(saveData.autoEffectCycleContent);
          saveData.autoEffectTimer = JSON.stringify(saveData.autoEffectTimer);
        }
  
        saveData.tideType = 0
      }

      API.fetchPost('/operatorPark/saveParkCloudTideChannel', saveData).then(
        res => {
          if (res.status === 1) {
            this.showToast('修改潮汐通道成功', 1, 1500);
            item.uiOpt.isEdit = false;
          } else {
            this.showToast(res.message, 2, 1500);
          }
        },
        err => {
          console.log(err);
        }
      );
    },
    testForm(item) {
      this.$refs['tideChannel'].validate(valid => {
        if (valid) {
          this.saveEdit(item);
        } else {
        }
      });
    },
    add0(number) {
      if (number.toString().length == 1) {
        return `0${number}`;
      } else {
        return number;
      }
    },
    linkToAddTideChannel() {
      this.$router.push({
        name: 'addTideChannel',
        query: this.$route.query
      });
    },
    back() {
      this.$router.push({
        name: 'allParkinglotInfo',
        query: this.$route.query
      });
    }
  }
};
